package com.uzhie.web.controller.websocket;

import org.apache.log4j.Logger;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Created by Coder on 2018/7/10.
 * socket 连接握手拦截器
 */
public class HandshakeInterceptor implements org.springframework.web.socket.server.HandshakeInterceptor {

    private Logger logger = Logger.getLogger(this.getClass());

    /**
     * 握手之前
     *
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @param webSocketHandler
     * @param map                WebSocketSession 的 Attribute <key,value>
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        logger.info("enter method beforeHandshake");
        if (serverHttpRequest instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) serverHttpRequest;
            HttpSession session = servletRequest.getServletRequest().getSession(true);
            String webSessionID;
            try {

                if (null != session.getAttribute("webSessionID")) {
                    webSessionID = (String) session.getAttribute("webSessionID");
                } else {
                    webSessionID = session.getId();
                }
                String userId = servletRequest.getServletRequest().getParameter("userId");
                logger.info("userId is " + userId);
                logger.info("handshakeInterceptor webSessionID is " + webSessionID);
                map.put("webSessionID", webSessionID);
                map.put("userId", userId);
            } catch (NullPointerException e) {
                logger.error("获取sessionID失败" + e);
                return false;
            }
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        logger.info("enter method afterHandshake");
    }
}
